package com.yanqu.road.server.manger;

import com.yanqu.road.entity.servercenter.whitelist.WhiteIP;
import com.yanqu.road.logic.bussiness.servercenter.IpInfoBussiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.List;

public class WhiteIpMgr extends TempMgr {

	private static List<String> playerWhiteIpList;

	private static List<String> consoleWhiteIpList;

	private static List<String> playerBlackIpList;

	/**
	 * 新后台白名单
	 */
	private static List<String> adminWhiteIpList;

	private static boolean isAllAccess = false;

	private static final String ALL_ACCESS_IP = "0.0.0.0";

	private static List<WhiteIP> whiteIPs = new ArrayList<>(); // IP白名单列表

	@Override
	public boolean init() throws Exception {
		return reload();
	}

	@Override
	public boolean stop() {
		return false;
	}

	@Override
	public boolean save() {
		return false;
	}

	@Override
	public boolean reloadData() {
		List<String> tempPlayerList = new ArrayList<>();
		List<String> tempConsoleList = new ArrayList<>();
		List<String> tempBlackList = new ArrayList<>();
		List<String> tempAdminList = new ArrayList<>();
		IpInfoBussiness.getWhiteIpList(tempPlayerList, tempConsoleList, tempBlackList, tempAdminList);
		playerWhiteIpList = tempPlayerList;
		consoleWhiteIpList = tempConsoleList;
		playerBlackIpList = tempBlackList;
		adminWhiteIpList = tempAdminList;
		if(consoleWhiteIpList.contains(ALL_ACCESS_IP)){
			isAllAccess = true;
		}
		whiteIPs = IpInfoBussiness.getWhiteIPs();
		return true;
	}

	@Override
	public boolean reloadConfig() throws Exception {
		return true;
	}

	/**
	 * 是否是黑名单
	 * @param ip
	 * @return
	 */
	public static boolean isBlackIp(String ip) {
		if (StringUtils.isNullOrEmpty(ip)) {
			return false;
		}
		for (String blackIp : playerBlackIpList) {
			if (ip.startsWith(blackIp)) {
				return true;
			}
		}
		return playerBlackIpList.contains(ip);
	}

	public static boolean isPlayerWhiteIp(String ip) {
		if(StringUtils.isNullOrEmpty(ip)){
			return false;
		}
		return playerWhiteIpList.contains(ip);
	}

	public static boolean isConsoleWhiteIp(String ip) {
		if(isAllAccess){
			return true;
		}else {
			if (StringUtils.isNullOrEmpty(ip)) {
				return false;
			}
			return consoleWhiteIpList.contains(ip);
		}
	}

	public static boolean isAdminWhiteIp(String ip) {
		if (StringUtils.isNullOrEmpty(ip)) {
			return false;
		}
		return adminWhiteIpList.contains(ip);
	}

	public static List<WhiteIP> getWhiteIPs() {
		return whiteIPs;
	}
}
